package com.lwlean.test.service.impl;

import com.lwlean.test.domain.Users;
import com.lwlean.test.mapper.UserMapper;
import com.lwlean.test.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.annotations.Param;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Random;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Created by lean on 16-12-6.
 */
@Service
public class UserServiceImpl implements UserService {

    private final Logger logger = LoggerFactory.getLogger(UserServiceImpl.class);

    ExecutorService pool = Executors.newFixedThreadPool(10);

    @Autowired
    private UserMapper userMapper;

    @Override
    public Users getUser(@Param("id") Long id) {
        return userMapper.getUser(id);
    }

    @Override
    public void addUser(@Param("user") Users user) {
        userMapper.addUser(user);
    }

    @Override
    public void dropUser(@Param("id") Long id) {
        userMapper.dropUser(id);
    }

    @Override
    @Transactional
    public void updateAndGetUser(Users users) {

        int pho = 0;

        for (int i=0; i< 100; i++) {
            pool.execute(new Runnable() {
                @Override
                public void run() {
                    final String phone = String.valueOf(new Random().nextInt(99)+1);
                    users.setId(1);
                    users.setPhone(phone);
                    userMapper.updateUsers(users);
                    Users user = userMapper.getUser(Long.valueOf(users.getId()));
                    logger.info("set:{} phone:{}",phone,user.getPhone());
                }
            });
        }
    }
}
